package group

import (
	"api/common"
	"api/pb/group"
	"context"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetGroupListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetGroupListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetGroupListLogic {
	return &GetGroupListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetGroupList 获取群聊列表
func (l *GetGroupListLogic) GetGroupList(req *types.GroupListRequest) (resp *types.GroupListResponse, err error) {
	// 1. 获取用户标识
	userID, err := common.GetUserIDFromCtx(l.ctx)
	if err != nil {
		return nil, err
	}
	// 2. 查询群聊列表
	groupList, err := l.svcCtx.GroupRPC.GetGroupList(l.ctx,
		&group.GroupListRequest{UserId: userID, Offset: req.Offset, Limit: req.Limit})
	if err != nil {
		return nil, err
	}
	// 3. 转换为响应格式
	resp = &types.GroupListResponse{
		Total: groupList.Total,
		List:  make([]*types.GroupInfo, 0),
	}
	// 4. 转换为响应格式
	for _, item := range groupList.Data {
		resp.List = append(resp.List, &types.GroupInfo{
			ID:         item.Id,
			Name:       item.Name,
			Desc:       item.Desc,
			Avatar:     item.Avatar,
			Status:     item.Status,
			JoinType:   item.JoinType,
			CreateTime: item.CreateAt,
			UpdateTime: item.UpdateAt,
		})
	}
	return resp, nil
}
